const { exec } = require('../db/index');

const getList = (author, keyword) => {
    //先返回假数据
    let sql = `select * from blogs;`
    return exec(sql).then(res => {
        return res
    })
}

const getDetail = (id) => {
    let sql = `select * from blogs where id=${id};`
    return exec(sql).then(res => {
        return res[0]
    })
}

const newBlog = (title, content, author) => {
    const createtime = Date.now()
    let sql = `insert into blogs(title, content, author, createtime) values ('${title}', '${content}', '${author}', '${createtime}');`
    // let sql = `insert into blogs(title, content, author) values ('标题1', '内容1', 'liguansheng');`
    return exec(sql).then(insertData => {
        // console.log(insertData)
        return {
            id: insertData.insertId
        }
    })
}

const updateBlog = ( id, title, content ) => {
    let sql = `update blogs set `
    if(title) {
        sql += `title='${title}'`
    }
    if(content) {
        if(title) {
            sql += `,`
        }
        sql += `content='${content}'`
    }
    sql += ` where id='${id}'`
    return exec(sql).then(updateData => {
        console.log(updateData)
        if (updateData.affectedRows > 0) {
            return true
        }
        return false
    })

}

const deleteBlog = (id, author) => {
    let sql = `delete from blogs where id='${id}' and author='${author}'`
    return exec(sql).then(delData => {
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog
}